$(function() {
    //目录展开与折叠
    tchpterFun();
    //右侧目录 笔记区域的展开与收起
    lrshFun();
    var buy = checkBuy($("#buyCourseId").val());
    //移除播放页直播的按钮
    $('*[data-slider] span.ml15').remove();
    // 移除页面右下方的反馈 二维码的浮层
    $('#js-slide-operation').remove();


    //如果是套餐课程，初始化显示的第一个课程名
    var courseTypeKey = $("#courseTypeKey").val();
    if(courseTypeKey=='PACKAGE'){//套餐首次加载目录
        var index = $("#index").val();
        var courseId = getIndexCourseId(index);
        $("#courseId").val(courseId);
        getPlayCatalog(courseId);
    }else{
        //普通课程首次加载目录
        var courseId = $("#courseId").val();
        getPlayCatalog(courseId);
    }

    $('body').on('click','#glim',function(){
        if($(this).children().text() == "关灯"){
            $(this).children('span').text("开灯");
            $('.u-bg').addClass('u-glim-bg')
        }else{
            $(this).children('span').text("关灯");
            $('.u-bg').removeClass('u-glim-bg')
        }
    }).on('click', 'h4[data-tab]', function () { //目录 笔记切换
        $(this).addClass('active').siblings().removeClass('active');
        var tab = $(this).data('tab');
        $('article[data-tab="' + tab + '"]').removeClass('hide').siblings().addClass('hide');
        if ('notes' == tab) {
            $('textarea[data-note]').val('');
            listCourseNote(1);
        }
    }).on('click', '[data-return]', function () { //返回
        history.back();
    }).on('click', '[data-slider]', function () { //目录最近学习 下载资料等
        return false;
    }).on('click', '.teacher_questions', function () { //提问
        var that = $(this).parent('a');
        //只试用与异步请求 打开新窗口
        var newWin = window.open('about:blank');
        checkBuyCourse(function(reult){
            if(reult.success){
                var packageId =0;
                //判断是否是套餐课程
                if($("#package-course-data-box").length>0){
                    packageId =$("#buyCourseId").val();
                }
                var courseId  = $(that).data("course-id");
                var catalogId  = $("#playId").val();
                var teacherId  = $(that).data("teacher-id");
                var parpm ="packageId="+packageId+"&courseId="+courseId+"&catalogId="+catalogId+"&teacherId="+teacherId;
                newWin.location.href=baseloaction+"/web/uc/qa/initSaveQuestionView?isCourse=true&type=1&"+parpm;
            }else {
                setTimeout(function () {
                    newWin.close();
                },100);
                icModale(0, '',reult.message)
            }


        })

    }).on('click', '[data-buy]', function () { //购买

    }).on('click', '.select-course', function () { //切换套餐课程
        var type = $(this).data('type');
        var index = parseInt($("#index").val());
        if(type==1){//上一个课程
            index = index -1;
        }else if(type==2){//下一个课程
            index = index + 1;
        }
        if(index < 0){
            icModale(0, '', '前面没有课程了');
            return;
        }
        var list = $("#package-course-data-box>li");
        if(index >= list.length){
            icModale(0, '', '后面没有课程了');
            return;
        }
        var _courseId = getIndexCourseId(index);
        getPlayCatalog(_courseId);
        //切换课程后将课程id改变为当前课程的id
        $("#courseId").val(_courseId);
        $("#index").val(index);
    }).on('click','#play-catalog .catalog-box',function () {//播放节点
        var _this = $(this);
        if(_this.hasClass('active')){
            return;
        }
        var id = _this.data('id');
        //执行播放
        goPlay(id);
    }).on('click','.exercise-btn-box',function (e) {//随堂练习
        var buyCourseId = $("#buyCourseId").val();
        var id = $(this).data('id');
        checkExercises(buyCourseId,id);
        e.stopPropagation();
    }).on('click','#teacher',function () {
        var newteacherId = $("#teacher").data("newteacherid");
        window.open(baseloaction+"/web/teacher/info?teacherId=" + newteacherId);
    }).on('click','i.fa-download',function(e){
        var _this = $(this);
        checkBuyCourse(function(result){
            if(result.success){
                var catalogId = _this.parent('span').data('catalogid');
                layer.open({
                    type: 1,
                    title: '提示',
                    content: "<p class='text-center'>确认要下载本节学习资料吗</p>",
                    btn: ['确认', '我再想想 '],
                    area: 'auto',
                    btnAlign: 'c',
                    shade: [0.3, '#000000'],
                    skin: 'lay_ppComment__wrap',
                    yes: function (index) {
                        var tempwindow=window.open();
                        tempwindow.location=_this.parent('span').data("url");
                        layer.close(index);
                    },
                    btn2: function (index) {
                        layer.close(index);
                    }
                });

            }else{
                guideBuy($('#buyCourseId').val(),"你还没有购买课程，无法下载资料，确认购买吗");

            }
        });
        e.stopPropagation();
    }).on('click',"#goToBack",function(){
        saveCourseLearnFlow(1);
        setTimeout(function(){
            window.location.href=baseloaction+"/web/uc/course/user/index";
        },1000)
    });

    /**
     * 获取下一个/上一个套餐课程的ID
     * @param index 下标
     * @return {*} 课程ID
     */
    function getIndexCourseId(index) {
        var list = $("#package-course-data-box>li");
        if(index >= 0 && index < list.length){
            var courseId = $(list[index]).data('course-id');
            $("#package-course-name-box").text($(list[index]).text());
            return courseId;
        }
        return 0;
    }

    /**
     * 加载目录
     * @param courseId 课程ID
     */
    function getPlayCatalog(courseId) {
        $.ajax({
            url:baseloaction +'/web/uc/play/getPlayCatalog',
            type:'post',
            data:{
                'buyCourseId':$("#buyCourseId").val(),
                'courseId':courseId
            },
            dataType:'text',
            beforeSend:function (XHR) {
                var loadText = '<div class="text-center pt10 pb10"><span class="loading"></span></div>';
                $("#play-catalog").html(loadText);
                return true;
            },
            success:function (result) {
                $("#play-catalog").html(result);
                //初始化目录滚动条
                $('.sidebar-collapse').slimScroll({
                    height: '100%',
                    railOpacity: 0.9,
                    alwaysVisible: false
                });
                // tooltips hover
                $('[data-toggle=tooltip]').tooltip({
                    container: "body",
                    html: true
                })
                //目录加载完成播放默认节点
                var catalogId = $("#catalogId").val();
                if(catalogId != 0){
                    $("#catalogId").val(0);
                    goPlay(catalogId);
                }else{
                    var playId = $("#playId").val();
                    if(playId==0){
                        var _list = $("#play-catalog>.cm-task-chapter dl>.tchpter-item-children>ol>li");
                        if(_list==null || _list.length<=0){
                            var _listParent = $("#play-catalog>.cm-task-chapter dl>.tchpter-item-parent>a");
                            if(_listParent==null ||_listParent.length<=0){
                                icModale(0,'','没有可播放的节点');
                            }else{
                                var em = _listParent[0];
                                goPlay($(em).data('id'));
                            }
                        }else{
                            var auditionList = $('span.badge-primary');
                            var _catalogId
                            if(auditionList!=null && auditionList!='undefined' && auditionList.length > 0){
                                var em = auditionList[0];
                                _catalogId = $(em).parent('a').data('id');
                            }else {
                                var em = _list[0];
                                _catalogId = $(em).find('a').data('id');
                            }
                            goPlay(_catalogId);
                        }
                    }else{
                        selectPlayNode(playId);
                    }
                }
            },
            error:function (error) {
                icModale(0,'','系统错误，目录加载失败');
            }
        });
    }

    //左右区域展开收起
    function lrshFun() {
        var _rsbtn = '.play-r-show-btn';
        $('body').on('click', '.play-menu-sh-btn', function () {
            $('.play-page-cont').addClass('lr-sh-state');
            $(_rsbtn).show();
        });
        $('body').on('click', _rsbtn, function () {
            $('.play-page-cont').removeClass('lr-sh-state');
            $(_rsbtn).hide();
        });
    }

    /**
     * 执行播放
     */
    function goPlay(catalogId) {
        var prevCatalogId = getPrevCatalogId(catalogId,true);
        var buyCourseId = $("#buyCourseId").val();
        var courseId = $("#courseId").val();
        $.ajax({
            url: baseloaction +'/web/uc/play/checkPlay',
            type:'post',
            dataType:'json',
            data:{
                'buyCourseId' : buyCourseId,
                'courseId' : courseId,
                'prevCatalogId' : prevCatalogId,
                'catalogId' : catalogId
            },
            success:function (result) {
                if(result.success==true){
                    var entity = result.entity;
                    if(entity.play==true || entity.audition ==true){
                        //保存上个节点的学习流水
                        saveCourseLearnFlow(1);
                        //设置播放标题
                        initTitle(catalogId);
                        $("#playId").val(catalogId);
                        $("#duration").attr("data-duration",courseId+'-' +catalogId);
                        $("#duration").val(entity.duration);
                        //设置播放节点的样式
                        selectPlayNode(catalogId);
                        //获取讲师ID
                        var teacherId = $("#catalog-"+catalogId).data('teacher');
                        //加载讲师
                        getTeacher(teacherId,courseId);
                        var sign = entity.sign;
                        //加载播放器
                        loadPlayData(sign);
                    }else{
                        if(entity.needBuy!=undefined&&entity.needBuy!=null&&(entity.needBuy==1||entity.needBuy==2)){
                            guideBuy(buyCourseId,result.message);
                        }else{
                            icModale(0,'',result.message);
                        }

                    }
                }else{
                    icModale(0,'',result.message);
                }
            },
            error:function (error) {
                icModale(0,'','系统错误，课程节点学习/播放失败');
            }
        });
    }

    /**
     * 加载讲师
     * @param teacherId 讲师ID
     */
    function getTeacher(teacherId,courseId) {
        setTimeout(function () {
            var _teacherId = $("#teacherId").val();
            if(teacherId == _teacherId || teacherId <=0 ){
                return;
            }
            $("#teacherId").val(teacherId);
            $("#qa-teacher-box").text('');
            if(buy){
                $.ajax({
                    url:baseloaction +'/web/uc/teacher/findQaTeacherById',
                    type:'post',
                    dataType:'json',
                    data:{'teacherId':teacherId},
                    success:function (reult) {
                        if(reult.success==true){
                            var teacher = reult.entity;
                            if(teacher!=null&&teacher.isQuestion=="1"){
                                var context = '<a href="javascript:void(0);" class="c-ccc quiz"  data-course-id="'+courseId+'" data-teacher-id='+teacher.id+'>';
                                context+='<img class="media-object img-circle" id="teacher" data-newteacherid='+teacher.id+' src="'+teacher.imageMap.pcUrlMap.large+'" width="28" height="28"/>';
                                context+='<span class="teacher_questions"><i class="iconfont icon-xieyoujian mr10 ml10"></i>去提问</span></a>';
                                $("#qa-teacher-box").html(context);
                            }
                        }else{
                            icModale(0,'',reult.message);
                        }
                    },
                    error:function (error) {
                        icModale(0,'','提问讲师加载失败');
                    }
                });
            }
        },500);
    }

    /**
     * 设置播放节点的样式
     * @param catalogId
     */
    function selectPlayNode(catalogId) {
        $('#play-catalog li').removeClass('active');
        $("#catalog-"+catalogId).addClass('active');
    }

    /***
     * 初始化播放窗最左上方的标题
     * @param catalogId 播放的节点ID
     */
    function initTitle(catalogId) {
        var catalogName = $("#catalog-" + catalogId).text();
        var title = '';
        if (courseTypeKey == 'PACKAGE') {
            title = '【套餐】' + $("#package-course-name-box").text();
        } else {
            title = $("#courseName").val();
        }
        title = title + ' - ' + $.trim(catalogName);
        $("#catalogName").text(title);
    }

    /**
     * 检查是否购买过课程
     */
    function checkBuyCourse(callback) {
        isLogin(function(){
            var courseId = $('#buyCourseId').val();
            $.ajax({
                url: baseloaction + '/web/course/checkUserBuyCourse',
                data: {'courseId': courseId},
                dataType: 'json',
                success: function (response) {
                    if ($.isFunction(callback)) callback(response);
                },
                error: function () {
                    icModale(0, '', '系统繁忙，请稍候再试');
                }
            })
        })

    }
    goNextPlay = goPlay;
});
var goNextPlay;

//推荐课程
recommendFn();

//推荐课程
function recommendFn(){
    var _ele = $('#ele-r-comment_bx').val();
    $('body').on('click', '#recommend', function () {
        layer.open({
            type:1,
            title:'推荐课程',
            area:['600px', '450px'],
            btn: ['立即报名'],
            shadeClose: true,
            skin: 'lay_ppComment__wrap',
            content: _ele,
            yes: function (index, layero) {

            }
        });
    });
}

/**
 * 验证课程是否验证过
 * @param _buyCourseId 购买的课程ID
 * @returns {boolean}
 */
function checkBuy(_buyCourseId){
    var isBuy = false;
    $.ajax({
        url:baseloaction +'/web/uc/play/check/buy',
        dataType:'json',
        type:'post',
        data:{
            'courseId':_buyCourseId
        },
        async:false,
        success:function (result) {
            isBuy = result.success;
        }
    });
    return isBuy;
}
